package com.googlecode.flealancemarket.tapestry.pages;

import com.googlecode.flealancemarket.core.tapestry.SpringBean;
import com.googlecode.flealancemarket.metamodel.Employer;
import com.googlecode.flealancemarket.metamodel.Freelancer;
import com.googlecode.flealancemarket.metamodel.User;
import com.googlecode.flealancemarket.service.commands.GetFullUserById;
import com.googlecode.flealancemarket.tapestry.pages.inbox.New;
import com.googlecode.flealancemarket.tapestry.util.Session;
import javax.persistence.Transient;
import org.apache.tapestry.annotations.ApplicationState;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.annotations.OnEvent;
import org.apache.tapestry.ioc.annotations.Inject;

public class Profile {

    @ApplicationState
    private Session session;

    @Transient
    private User user;
    private Employer employer;
    private Freelancer freelancer;
    private boolean usersPage;

    @InjectPage
    private New newMessage;

    @Inject
    @SpringBean("GetFullUserById")
    private GetFullUserById getFullUserById;

    Object onActivate(Object[] params){
        Long userId;
        if(params.length==0) {
            if(session.getUserId()==0){
                session.setMessage("You have to be logged in in order to see your profil page.");
                return Login.class;
            }
            usersPage = true;
            userId = session.getUserId();
        } else {
            usersPage = false;
            userId = Long.parseLong((String)params[0]);
        }
        getFullUserById.setId(userId);
        user = getFullUserById.execute();
        if(user==null){
            session.setMessage("There's no such user");
            return Categories.class;
        }
        if(userIsEmployer())
            employer = (Employer)user;
        else
            freelancer = (Freelancer)user;
        return null;
    }

    public Long getId(){
        return session.getUserId();
    }
    public User getUser(){
        return user;
    }
    public boolean getUsersPage(){
        return usersPage;
    }
    public boolean userIsEmployer(){
        return (user instanceof Employer);
    }
    public Employer getEmployer(){
        return employer;
    }
    public Freelancer getFreelancer(){
        return freelancer;
    }

    @OnEvent(component="sendMessage")
    Object replyMessage(String username){
        //newMessage.setUsername(user.getUsername());
        newMessage.setUsername(username);
        return newMessage;
    }
}
